package com.zh.ssmshirofreemarker.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zh.ssmshirofreemarker.Utils.ResponseUtil;
import com.zh.ssmshirofreemarker.entity.Role;
import com.zh.ssmshirofreemarker.entity.User;
import com.zh.ssmshirofreemarker.entity.UserRole;
import com.zh.ssmshirofreemarker.mapper.RoleMapper;
import com.zh.ssmshirofreemarker.mapper.UserMapper;
import com.zh.ssmshirofreemarker.mapper.UserRoleMapper;
import com.zh.ssmshirofreemarker.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZH
 * @since 2018-07-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleMapper roleMapper;

    public Page<User> selectUserPage(Page<User> page,User user){
        // 不进行 count sql 优化，解决 MP 无法自动优化 SQL 问题
        // page.setOptimizeCountSql(false);
        // 不查询总记录数
        // page.setSearchCount(false);
        // 注意！！ 分页 total 是经过插件自动 回写 到传入 page 对象
        return page.setRecords(userMapper.selectUserList(page,user));
    }

    @Override
    public ResponseUtil addUser(User user) {

        boolean flag = user.getUsername() != null && !user.getUsername().equals("") && user.getPassword()!=null
                       &&user.getPassword().equals("");
        if(flag){
            return new ResponseUtil(ResponseUtil.FAIL_CODE,ResponseUtil.FAIL_STR,"用户名、密码不能为空");
        }

        int count = 0;
        if(userMapper.selectCount(new EntityWrapper<User>().eq("username",user.getUsername())) > 0){
             return new ResponseUtil(ResponseUtil.FAIL_CODE,ResponseUtil.FAIL_STR,"用户名重复,请重新输入");
        }
        String currentUserName = "";
        if( SecurityUtils.getSubject().getPrincipal() != null){
            currentUserName = SecurityUtils.getSubject().getPrincipal().toString();
        } else {
            currentUserName = user.getUsername();
        }
        String algorithmName = "MD5";    //使用的加密算法
        Object source = user.getPassword(); //密码的明文
        int hashIterations = 1;          //加密的次数
        ByteSource salt = ByteSource.Util.bytes(user.getUsername());              //盐值
        Object result = new SimpleHash(algorithmName, source, salt, hashIterations); // 加密算法，密码的明文，加密的盐值，加密的次数
        user.setPassword(result.toString());
        Date currentDate = new Date();
        user.setCreateUser(currentUserName);
        user.setCreateTime(currentDate);
        user.setUpdateTime(currentDate);
        user.setUpdateUser(currentUserName);
        try{
          count = userMapper.insert(user);
        } catch (Exception e){
            e.printStackTrace();
        }
        if(count > 0){
            return new ResponseUtil(ResponseUtil.SUCCESS_CODE,ResponseUtil.SUCCESS_STR,ResponseUtil.SUCCESS_STR);
        }
        return new ResponseUtil(ResponseUtil.FAIL_CODE,ResponseUtil.FAIL_STR,ResponseUtil.FAIL_STR);
    }

    @Override
    public boolean deleteUserById(User user) {
        return userMapper.updateDeleteFlagById(user);
    }

    @Override
    public boolean deleteUsersByIds(String ids) {
        User user = getUserAndSetTime();
        user.setDeleteFlag(1);
        return userMapper.updateDeleteFlagByIds(ids.split(","),user);
    }

    @Override
    public boolean openUsersByIds(String ids) {
        User user = getUserAndSetTime();
        user.setDeleteFlag(0);
        return userMapper.updateDeleteFlagByIds(ids.split(","),user);
    }

    @Override
    public List<Map<String, Object>> getAllRoleAndSignHasRole(Long id) {
        List<Map<String,Object>> result = new ArrayList<>();
        List<UserRole> userRoles = userRoleMapper.selectList(new EntityWrapper<UserRole>().eq("user_id",id));
        List<Long> roleIds = new ArrayList<>();
        for(UserRole ur : userRoles){
            roleIds.add(ur.getRoleId());
        }
        List<Role> roles = roleMapper.selectList(new EntityWrapper<Role>().eq("delete_flag",0));
        for(Role r : roles){
            Map<String,Object> temp = new HashMap<>();
            temp.put("roleId",r.getRoleId());
            temp.put("roleName",r.getRoleName());
            temp.put("desc",r.getDesc());
            if(roleIds.contains(r.getRoleId())){
               temp.put("isHas",true);
            } else {
                temp.put("isHas",false);
            }
            result.add(temp);
        }
        return result;
    }

    @Override
    public boolean checkUserName(User user) {
        if(user.getUsername()!= null && !user.getUsername().equals("")){
            Integer count = selectCount(new EntityWrapper<User>().eq("username",user.getUsername()));
            if(count != null && count <= 0){
               return true;
            }
        }
        return false;
    }


    private User getUserAndSetTime() {
        User user = new User();
        user.setUpdateUser(SecurityUtils.getSubject().getPrincipal().toString());
        user.setUpdateTime(new Date());
        return user;
    }

}
